﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;

namespace MendeleyClient.Phone
{
    public class DocumentRecord
    {
        public string title;
        public string value;
        public string publication;
        public string year;
        public string link;
        public string authors;

        public DocumentRecord(string title, string value, string publication, string year, string link, string authors)
        {
            this.title = title;
            this.value = value;
            this.publication = publication;
            this.year = year;
            this.link = link;
            this.authors = authors;
        }

        static public List<DocumentRecord> Parse(string str)
        {
            var records = new List<DocumentRecord>();

            for (; ; )
            {
                var startIndx = str.IndexOf("{");
                var endIndx = str.IndexOf("}]}") + 2;
                if (startIndx < 0 || endIndx <= startIndx)
                {
                    break;
                }
                var recordStr = str.Substring(startIndx, endIndx - startIndx);
                recordStr = recordStr.Replace("{", "");
                recordStr = recordStr.Replace("}", "");

                if (recordStr.Length > 0)
                {
                    recordStr = recordStr.Replace("\"title\":", "");
                    recordStr = recordStr.Replace("\"value\":", "");
                    recordStr = recordStr.Replace("\"publication\":", "");
                    recordStr = recordStr.Replace("\"year\":", "");
                    recordStr = recordStr.Replace("\"link\":", "");
                    recordStr = recordStr.Replace("\"authors\":", "");
                    recordStr = recordStr.Replace("\"", "");

                    var recordAuthorsStr = recordStr.Substring(recordStr.IndexOf("["), recordStr.IndexOf("]") - recordStr.IndexOf("["));
                    recordAuthorsStr = recordAuthorsStr.Replace("[", "");
                    recordAuthorsStr = recordAuthorsStr.Replace("]", "");
                    recordAuthorsStr = recordAuthorsStr.Replace("forename:", "");
                    recordAuthorsStr = recordAuthorsStr.Replace(",surname:", " ");

                    var kv = recordStr.Split(',');

                    var record = new DocumentRecord(kv[0], kv[1], kv[2], kv[3], kv[4], recordAuthorsStr); 
                    records.Add(record);
                }
                else
                {
                    break;
                }
                str = str.Substring(endIndx+1);
            }

            return records;
        }
    }
}
